<template>
  <div class="goods-image">

    <!-- 显示在右侧的放大之后的区域 -->
    <div class="large"
         v-show="!isOutside"
    :style="[{backgroundImage:'url('+images+')', backgroundPosition: `-${position.x*2}px -${position.y*2}px`}]"></div>

    <div class="middle" ref="target">
      <img :src="images" alt="" />
      <!-- 移动遮罩 -->
      <div class="layer" ref="target" v-show="!isOutside " :style="{ left:position.x+'px', top: position.y+'px' }"></div>
    </div>
  </div>
</template>

<script>
import {useMouseInElement} from '@vueuse/core'

export default {
  data() {
    return {
      isOutside: true,
      elementX: 0,
      elementY: 0,
      images: require('../../assets/OIP-C.jpg'),
      position: {
        x: 0,
        y: 0,
      },
    };
  },
  watch: {
    elementX(newVal, oldVal) {
      this.position.x = newVal < 0 ? 0 : newVal -100;
      this.position.x = newVal > 200 ? 200 : newVal -100;
    },
    elementY(newVal, oldVal) {
      this.position.y = newVal < 0 ? 0 : newVal -100;
      this.position.y = newVal > 200 ? 200 : newVal -100;
    }
  } ,
  mounted() {
    const el = this.$refs.target;
    const {isOutside,elementX,elementY} = useMouseInElement(el) // useMouseInElement(指定的区域)鼠标进入的位置
    this.isOutside = isOutside;
    this.elementX = elementX;
    this.elementY = elementY;
  },
};
</script>

<style lang="scss" scoped>
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;
  z-index: 500;
  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0,0,0,0.1);
    background-repeat: no-repeat;
    // 放大一倍
    background-size: 800px 800px;
    background-color: #f8f8f8;
  }
  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;
    img{
      width: 400px;
      height: 400px;
    }
    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0,0,0,.2);
      left: 0;
      top: 0;
      // 可以移动
      position: absolute;
    }
  }
}
</style>
